package com.heima.behavior.service.impl;

import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.behavior.service.ApBehaviorEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询行为实体
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId != null) {
            //	不为空 使用userId查询 行为实体 (refId = 用户id     type = 用户类型  )
            Query refId = Query.query(Criteria.where("refId").is(userId)
                    .and("type").is(1));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(refId, ApBehaviorEntry.class);
            if (apBehaviorEntry == null) {
                //  如果不存在基于userId创建实体数据
                ApBehaviorEntry apBehaviorEntry1 = new ApBehaviorEntry();
                apBehaviorEntry1.setType((short) 1);
                apBehaviorEntry1.setRefId(userId);
                apBehaviorEntry1.setCreatedTime(new Date());
                //添加宝MongoDB中
                ApBehaviorEntry save = mongoTemplate.save(apBehaviorEntry1);
                //  返回行为实体
                return save;
            }
            return apBehaviorEntry;
        }
        if (equipmentId != null) {
            Query refId = Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(0));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(refId, ApBehaviorEntry.class) ;
            if (apBehaviorEntry == null) {
                //  如果不存在基于userId创建实体数据
                ApBehaviorEntry apBehaviorEntry1 = new ApBehaviorEntry();
                apBehaviorEntry1.setType((short) 0);
                apBehaviorEntry1.setRefId(equipmentId);
                apBehaviorEntry1.setCreatedTime(new Date());
                //添加宝MongoDB中
                ApBehaviorEntry save = mongoTemplate.save(apBehaviorEntry1);
                //  返回行为实体
                return save;
            }
            return apBehaviorEntry;
        }
        //如果userId和设备id都不存在  返回null 调用者需要判断null
        return null;
    }
}
